﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BingVis.Common;
using System.IO;

namespace BingVis.GoogleTransit
{
    public class GTFSFile : IGTFSFile, IDisposable
    {
        private string[] _fileContents;
        private StreamReader _fileStream;

        public GTFSFile(string fileName, string[] fileContents)
        {
            FullPath = fileName;
            FileName = Path.GetFileName(fileName);
            _fileContents = fileContents;
        }

        public GTFSFile(string fileName)
            : this(new FileInfo(fileName))
        {
            
        }

        public GTFSFile(FileInfo file)
        {
            FullPath = file.FullName;
            FileName = Path.GetFileName(file.FullName);
            _fileStream = File.OpenText(file.FullName);            
        }

        #region IGTFSFile Members

        public string FullPath { get; private set; }
        public string FileName { get; private set; }
        public IEnumerable<string> Lines 
        {
            get
            {
                if (_fileContents != null)
                {
                    foreach (var line in _fileContents)
                    {
                        yield return line;
                    }
                }
                else if (_fileStream != null)
                {
                    while (!_fileStream.EndOfStream)
                        yield return _fileStream.ReadLine();
                }
                else
                    yield return "";
            }
        }

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Deconstructor... ?
        /// </summary>
        ~GTFSFile()
        {
            if (_fileStream != null)
            {
                _fileStream.Close();
                _fileStream = null;
            }

            _fileContents = null;
        }

        public void Dispose()
        {
            if (_fileStream != null)
            {
                _fileStream.Close();
                _fileStream = null;
            }

            _fileContents = null;
        }

        #endregion
    }
}
